import configapi from "@/apis/getconfigsapi";
import { InitMedias, ComponentSysNames } from "@/utils/constant";
import { isReallyNull } from "@/utils/utils";
import Vue from "vue";
let RequestData = {
  data: {},
  method: "POST" || "GET"
};

let configsprocess = {
  configs: [],
  async getData(sysno) {
    let _this = this;
    // #region 商品组件
    let RequestDatas = { ...RequestData, companysysno: sysno };
    let proc = _this.configs.filter((e, index) => {
      if (e.SysName === ComponentSysNames.productcopt) {
        return true;
      } else {
        return false;
      }
    });
    // let prs = []
    let ProductSysNos = [];
    for (let index = 0; index < proc.length; index++) {
      let e = proc[index];
      e.DataList = [];
      ProductSysNos = ProductSysNos.concat(e.ConfigData.productsysnos);
    }
    // #endregion
    let tagproc = _this.configs.filter(
      (e, index) => e.SysName === ComponentSysNames.tagproductcopt
    );
    // let tagprs = []
    let ProductTagSysNos = [];
    for (let index = 0; index < tagproc.length; index++) {
      let e = tagproc[index];
      e.DataList = [];
      let tagsysnos = [];
      e.ConfigData.taglist.map(a => {
        e.ConfigData.taglist[0].selected = false;
        tagsysnos.push(a.sysno);
      });
      e.ConfigData.taglist[0].selected = true;
      ProductTagSysNos = ProductTagSysNos.concat(tagsysnos);
    }
    let reqdata = Object.assign({}, RequestDatas);
    reqdata.method = "post";
    reqdata.showLoadding = false;
    reqdata.data = {
      ProductDataList: {
        SysNos: ProductSysNos
      },
      ProductTagDataList: {
        SysNos: ProductTagSysNos
      }
    };
    if (ProductSysNos.length > 0 && ProductTagSysNos.length > 0) {
      reqdata.data.DataType = 1 | 2;
    } else if (ProductTagSysNos.length > 0) {
      reqdata.data.DataType = 2;
    }
    if (ProductSysNos.length > 0 || ProductTagSysNos.length > 0) {
      let res = await configapi.getProductData(reqdata);
      if (res.Success) {
        let respdata = res.Data;
        let procdata = respdata.ProductDataList.ProductList;
        if (!isReallyNull(procdata)) {
          for (let index = 0; index < proc.length; index++) {
            let element = proc[index];
            element.ConfigData.productsysnos.map((e, psindex) => {
              let productdata = procdata.filter(prod => e === prod.SysNo);
              if (productdata) {
                element.DataList = element.DataList.concat(productdata);
              }
            });

            // let proddata = procdata.filter(e => {
            //   if (element.ConfigData.productsysnos.indexOf(e.SysNo) > -1) {
            //     debugger
            //     element.DataList.push(e)
            //     return true
            //   } else {
            //     return false
            //   }
            // })
            // element.DataList = proddata
          }
        }
        let tagprdata = respdata.ProductTagDataList.ProductTagList;
        if (!isReallyNull(tagprdata)) {
          for (let index = 0; index < tagproc.length; index++) {
            let element = tagproc[index].ConfigData.taglist;
            for (let j = 0; j < element.length; j++) {
              let prt = element[j];
              let data = tagprdata.find(e => e.SysNo === prt.sysno);
              if (data) {
                if (
                  JSON.parse(prt.showall) === 0 &&
                  data.ProductInfoList.length > JSON.parse(prt.showcount)
                ) {
                  data.ProductInfoList = data.ProductInfoList.slice(
                    0,
                    JSON.parse(prt.showcount)
                  );
                }
                if (!isReallyNull(prt.name)) {
                  data.Name = prt.name;
                }
                tagproc[index].DataList.push(data);
              }
              if (!isReallyNull(tagproc[index].DataList[j])) {
                prt.ProductInfoList =
                  tagproc[index].DataList[j].ProductInfoList;
              }
            }
          }
        }
        console.log(_this.configs);
      } else {
        _this.$toast(res.Message);
      }
      for (let iterator of _this.configs) {
        let tempdatas = [...iterator.DataList];
        delete iterator.DataList;
        Vue.set(iterator, "DataList", tempdatas);
      }
    }
    let news = _this.configs.filter((e, index) => {
      if (
        e.SysName === ComponentSysNames.newscopt &&
        e.ConfigData.type >> 0 === 1
      ) {
        return true;
      } else {
        return false;
      }
    });
    if (news.length > 0) {
      let newssysnos = [];
      news.map(e => {
        if (e.ConfigData.items.length > 0) {
          e.ConfigData.items.map(it => {
            newssysnos.push(it.topicsysno);
          });
        }
      });
      if (newssysnos.length > 0) {
        let newdata = Object.assign({}, RequestDatas);
        newdata.method = "post";
        newdata.showLoadding = false;
        newdata.data = newssysnos;
        let res = await configapi.getNews(newdata);
        if (res.Success) {
          let data = res.Data;
          if (data.length > 0) {
            news.map(e => {
              let temp = [];
              if (e.ConfigData.items.length > 0) {
                e.ConfigData.items.map(it => {
                  let tnews = data.find(
                    nd => nd.SysNo === JSON.parse(it.topicsysno)
                  );
                  if (tnews) {
                    it.title = tnews.Title;
                    it.publishdate = tnews.PublishDateStr;
                    it.defaultimage = tnews.FullDefaultImage;
                    temp.push(it);
                  }
                });
              }
              e.ConfigData.items = temp;
            });
          }
        } else {
          news.map(e => {
            e.ConfigData.items = [];
          });
        }
      }
    }
    let fullnews = _this.configs.filter((e, index) => {
      if (
        e.SysName === ComponentSysNames.newscopt &&
        e.ConfigData.type >> 0 === 3
      ) {
        return true;
      } else {
        return false;
      }
    });
    if (fullnews.length > 0) {
      let fnewdata = Object.assign({}, RequestDatas);
      fnewdata.method = "get";
      fnewdata.showLoadding = false;
      let res = await configapi.getFourNews(fnewdata);
      if (res.Success) {
        let data = res.Data;
        if (data.length > 0) {
          fullnews.map(e => {
            let temp = [];
            data.map(ne => {
              let it = {
                topicsysno: ne.SysNo,
                title: ne.Title,
                publishdate: ne.PublishDateStr,
                defaultimage: ne.FullDefaultImage
              };
              temp.push(it);
            });
            e.ConfigData.items = temp;
          });
        }
      } else {
        news.map(e => {
          e.ConfigData.items = [];
        });
      }
    }

    let coups = _this.configs.filter((e, index) => {
      if (e.SysName === ComponentSysNames.couponercopt) {
        return true;
      } else {
        return false;
      }
    });
    if (coups.length > 0) {
      let coupsysnos = [];
      coups.map(e => {
        coupsysnos.push(e.ConfigData.couponsysno);
      });
      if (coupsysnos.length > 0) {
        let removecoupsysno = []; // 后台请求无此优惠券信息，需要删除的优惠券的sysno;
        let cpsdata = Object.assign({}, RequestDatas);
        cpsdata.method = "post";
        cpsdata.showLoadding = false;
        cpsdata.data = coupsysnos;
        let res = await configapi.getCouponsData(cpsdata);
        if (res.Success) {
          var recoup = res.Data;
          coups.map(c => {
            let rec = recoup.find(
              rec => rec.SysNo === c.ConfigData.couponsysno
            );
            if (rec) {
              c = { ...c, ...rec };
              c.ConfigData.couponinfo.amount = rec.FaceValue;
              c.ConfigData.couponinfo.name = rec.Name;
              c.ConfigData.couponinfo.userdatestr = rec.PortDateStr;
              c.ConfigData.couponinfo.orderamount = rec.UseOrderAmountLimit;
              c.ConfigData.istake = rec.IsTake;
            } else {
              removecoupsysno.push(c.ConfigData.couponsysno);
            }
          });
          if (removecoupsysno.length > 0) {
            _this.configs = _this.configs.filter(
              e =>
                e.SysName !== ComponentSysNames.couponercopt ||
                removecoupsysno.indexOf(e.ConfigData.couponsysno) === -1
            );
          }
        }
      }
    }
  },
  async GetWebHomeConfig(sysno) {
    let _this = this;
    let result = await configapi.getWebHomeConfig(sysno);
    if (result.Success && result.Data) {
      if (result.Data.length > 0) {
        if (!isReallyNull(result.Data[0]["IsFullScreen"])) {
          _this._IsFullScreen = result.Data[0]["IsFullScreen"];
          _this._BackGroundColor = result.Data[0]["BackGroundColor"];
          _this._BackGroundImage = result.Data[0]["BackGroundImage"];
          if (_this._IsFullScreen) {
            // wepy.setNavigationBarColor({
            //   frontColor: '#ffffff',
            //   backgroundColor: '#ffffff',
            //   animation: {
            //     duration: 0
            //   }
            // })
          }
          result.Data.splice(0, 1);
        }
        result.Data.map(e => {
          if (!isReallyNull(e.SysName)) {
            e.ConfigData = JSON.parse(e.ConfigData);
          }
        });
      }
      _this.configs = result.Data;
      var IsAppCompanyAccount = true;
      let newconfigsCouponer = [];
      _this.configs.map(e => {
        if (e.SysName === ComponentSysNames.gratextadscopt) {
          e.Points = [];
          e.ConfigData.items.map(a => {
            e.Points.push(0);
          });
          e.Points[0] = 1;
        }
        if (e.SysName === ComponentSysNames.richtextcopt) {
          e.ConfigData.content = e.ConfigData.content.replace(
            /<img/g,
            '<img style="max-width:100% !important;height:auto;display:block"'
          );
        }
        if (e.SysName === ComponentSysNames.textcopt) {
          e.ConfigData.text = e.ConfigData.text.replace(/<br\/>/g, "\n");
        }
        if (
          !IsAppCompanyAccount &&
          e.SysName === ComponentSysNames.couponercopt
        ) {
        } else {
          newconfigsCouponer.push(e);
        }
      });
      _this.configs = newconfigsCouponer.concat([]);
      // 图文广告自适应高度
      let tempprolist = [];
      let grat = _this.configs.filter(
        e => e.SysName === ComponentSysNames.gratextadscopt
      );
      if (grat.length > 0) {
        grat.map(e => {
          e.ConfigData.fixHight = 460;
          tempprolist.push(
            new Promise(resolve => {
              let data = {
                height: e.ConfigData.items[0].imageinfo.height,
                width: e.ConfigData.items[0].imageinfo.width
              };
              resolve(data);
            })
          );
          e.ConfigData.fixHight =
            1 *
            ((e.ConfigData.items[0].imageinfo.height * 750) /
              e.ConfigData.items[0].imageinfo.width);
        });
        if (tempprolist.length > 0) {
          Promise.all(tempprolist).then(a => {
            for (let index = 0; index < a.length; index++) {
              const element = a[index];
              grat[index].ConfigData.fixHight =
                1 * ((element.height * 750) / element.width);
            }
          });
        }
      }
      await _this.getData(sysno);
    }
  },
  Init(sysno) {
    // if (this.configs.length === 0) {
    this.GetWebHomeConfig(sysno);
    //}
  }
};
export default configsprocess;
